package com.zoweunion.mechanic.service.order.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.zoweunion.mechanic.dao.app.AppDao;
import com.zoweunion.mechanic.util.*;
import com.zoweunion.mechanic.util.constants.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.zoweunion.mechanic.dao.order.KFOrderDao;
import com.zoweunion.mechanic.dao.order.TZOrderDao;
import com.zoweunion.mechanic.model.User;
import com.zoweunion.mechanic.service.order.TZOrderService;

/**
 * 听诊工单业务类
 *
 * @author Administrator
 */
@Service
@Transactional
public class TZOrderServiceImpl implements TZOrderService {

    @Autowired
    private TZOrderDao tZOrderDao;
    @Autowired
    private KFOrderDao kFOrderDao;
    @Autowired
    private AppDao appDao;


    @Transactional(readOnly = true)
    public Map<String, Object> listByStatus(Map<String, Object> reqMap) {

        //1.设置分页的limit和offset
        Map<String, Object> pageMap = Page.appPage(reqMap.get("pageSize").toString(),
                reqMap.get("currentPage").toString());
        reqMap.put("pageSize", pageMap.get("limit"));
        reqMap.put("currentPage", pageMap.get("offset"));
        int limit = Integer.valueOf(pageMap.get("limit").toString());
        //2.查询总记录数
        int total = tZOrderDao.countBycondition(reqMap);

        //3执行分页查询
        List<Map<String, Object>> orderList = tZOrderDao.listByStatus(reqMap);

        //4根据工单id关联查询故障列表
        if (total > 0) {
            for (Map<String, Object> orderMap : orderList) {
                orderMap.put("order_id", orderMap.get("id"));

                List<Map<String, Object>> orderFaultList = kFOrderDao.getOrderFaultByOrderId(orderMap);
                orderMap.put("faultInfo", orderFaultList);

                // 工单图片
                List<Map<String, Object>> imgList = appDao.findOrderImg(orderMap);
                orderMap.put("img_info", imgList);

                //5根据工单id关联查询修工信息
                List<Map<String, Object>> orderRepairmanList = kFOrderDao.getOrderRepairmanByOrderId(orderMap);
                orderMap.put("repairmanInfo", orderRepairmanList);
            }
        }
        //增加车辆信息包括车辆品牌型号设备号
        orderList.forEach(orderMap -> {
            List<Map<String, Object>> carInfoList = kFOrderDao.getCarInfo(orderMap);

            orderMap.put("carInfoList", carInfoList);

        });
        //查询听诊的名字
        orderList.forEach(orderMap -> {
            String name = kFOrderDao.getTZname(orderMap);

            orderMap.put("tz_name", name);

        });
        //查询订单的故障类型
        orderList.forEach(orderMap -> {
            List<String> dictionaries_nameList = kFOrderDao.getDictionariesName(orderMap);

            orderMap.put("dictionaries_nameList", dictionaries_nameList);

        });
        //包装结果集  总条数 总页数 数据集
        HashMap<String, Object> resultMap = new HashMap<String, Object>();
        int pages = (total + limit - 1) / limit;//总页数  需要有余进一
        //获取当前登入用户
        User user = (User) reqMap.get("user");
        //获取当前用户的角色
        String r_id = user.getR_id();
        //将符合地域要求的工单分发给对应的客服
        //判断当前登入用户是否 为听诊
        if (r_id.equals(Constants.ROLE_TZ)) {
            //获取当前修工所擅长的故障类型
            String speciality = user.getSpeciality() == null ? "" : user.getSpeciality();
            //当前听诊所负责的区域
            String area = user.getArea() == null ? "" : user.getArea();
            if (!"".equals(area)) {
                //todo
                List<Map<String, Object>> resultList = orderList.stream()
                        .filter(map -> {
                            if (map.get("area") == null) {
                                return true;
                            }
//                            if (area.contains(map.get("area").toString())) {
//                                return true;
//                            } else {
//                                return false;
//                            }
                            //判断该工单所在的地域属于哪一类省份(按省,自治区,直辖市分类)
                            if (map.get("area").toString().contains("省")) {
                                int index = map.get("area").toString().indexOf("省");
                                //截取该工单所对应的省份
                                String province = map.get("area").toString().substring(0, index + 1);
                                //查看该工单所对应的大区
                                String region_name = kFOrderDao.getRegionByProvince(province);
                                @SuppressWarnings("unchecked")
                                List<String> dictionaries_nameList = JSONObject.parseObject(map.get("dictionaries_nameList").toString(), List.class);
                                //判断当前工单的故障类型是否属于修工的特长之一
                                Boolean flag = dictionaries_nameList.stream().anyMatch(x -> {
                                    return speciality.contains(x);
                                });
                                //若听诊所服务的地域包含该工单所在的省份,则返回true,否则返回false,此处需注意返回的工单信息必须包含故障类型,否则报空指针异常.
                                if (area.contains(region_name) && flag) {
                                    return true;
                                } else {
                                    return false;
                                }
                            } else if (map.get("area").toString().contains("区")) {
                                int index = map.get("area").toString().indexOf("区");
                                String province = map.get("area").toString().substring(0, index + 1);
                                String region_name = kFOrderDao.getRegionByProvince(province);
                                @SuppressWarnings("unchecked")
                                List<String> dictionaries_nameList = JSONObject.parseObject(map.get("dictionaries_nameList").toString(), List.class);
                                //判断当前工单的故障类型是否属于修工的特长之一
                                Boolean flag = dictionaries_nameList.stream().anyMatch(x -> {
                                    return speciality.contains(x);
                                });
                                if (area.contains(region_name) && flag) {
                                    return true;
                                } else {
                                    return false;
                                }
                            } else {
                                int index = map.get("area").toString().indexOf("市");
                                String province = map.get("area").toString().substring(0, index + 1);
                                String region_name = kFOrderDao.getRegionByProvince(province);
                                @SuppressWarnings("unchecked")
                                List<String> dictionaries_nameList = JSONObject.parseObject(map.get("dictionaries_nameList").toString(), List.class);
                                //判断当前工单的故障类型是否属于修工的特长之一
                                Boolean flag = dictionaries_nameList.stream().anyMatch(x -> {
                                    return speciality.contains(x);
                                });
                                if (area.contains(region_name) && flag) {
                                    return true;
                                } else {
                                    return false;
                                }
                            }
                        }).collect(Collectors.toCollection(ArrayList::new));
                resultMap.put("total", total);
                resultMap.put("pages", pages);
                resultMap.put("list", resultList);
            } else {
                resultMap.put("total", total);
                resultMap.put("pages", pages);
                resultMap.put("list", orderList);
            }
        } else {
            resultMap.put("total", total);
            resultMap.put("pages", pages);
            resultMap.put("list", orderList);
        }
        return resultMap;

    }


    @Override
    public int doRepair(Map<String, Object> reqMap) {
        int result = 0;
        //1创建总工单
        Map<String, Object> parentOrderMap = kFOrderDao.getOrderInfoByOrderId(reqMap);
        reqMap.put("order_id", UuidUtil.get32UUID());
        reqMap.put("order_no", Tool.markOrderNo("P", Constants.ORDER_TYEP_FX + ""));
        reqMap.put("order_type", Constants.ORDER_TYEP_FX);//返修工单
        reqMap.put("order_status", Constants.ORDER_STATUS_PJ);//待配件
        reqMap.put("urgent", 0);//不加急
        reqMap.put("u_t_id", reqMap.get("current_user_id"));
        reqMap.put("c_id", parentOrderMap.get("c_id"));
        reqMap.put("o_id", parentOrderMap.get("o_id"));
        reqMap.put("d_id", parentOrderMap.get("d_id"));
        reqMap.put("u_s_id", parentOrderMap.get("u_s_id"));
        reqMap.put("parent_id", parentOrderMap.get("id"));
        reqMap.put("user_name", parentOrderMap.get("contacts"));
        reqMap.put("p_type", parentOrderMap.get("p_type"));
        reqMap.put("mobile_phone", parentOrderMap.get("phone"));
        reqMap.put("address", parentOrderMap.get("address"));
        result += kFOrderDao.createOrder(reqMap);

        //2创建工单明细
        reqMap.put("order_detail_id", UuidUtil.get32UUID());
        result += kFOrderDao.createOrderDetail(reqMap);

        //3 查询父工单的故障   创建新的故障关联
        parentOrderMap.put("order_id", parentOrderMap.get("id"));
        List<Map<String, Object>> faultList = kFOrderDao.getOrderFaultByOrderId(parentOrderMap);
        if (faultList != null && faultList.size() > 0) {
            for (Map<String, Object> map : faultList) {
                map.put("order_fault_id", UuidUtil.get32UUID());
                map.put("current_user_id", reqMap.get("current_user_id"));
                map.put("order_id", reqMap.get("order_id"));
                map.put("s_id", reqMap.get("s_id"));
                result += kFOrderDao.createOrderFault(map);
            }
        }

        //4创建修工关联
        if (reqMap.get("repairmanInfo") != null && !reqMap.get("repairmanInfo").equals("")) {
            List<Map<String, Object>> repairmanList = (List<Map<String, Object>>) reqMap.get("repairmanInfo");
            for (Map<String, Object> repairmanMap : repairmanList) {
                repairmanMap.put("repairman_id", UuidUtil.get32UUID());
                repairmanMap.put("current_user_id", reqMap.get("current_user_id"));
                repairmanMap.put("order_id", reqMap.get("order_id"));
                result += kFOrderDao.createRepairman(repairmanMap);
            }
        }

        return result;
    }

}
